<template>
  <div>
    <!-- 1 -->
    <el-form ref="form" :model="deptForm" :rules="deptRules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <!-- 2 -->
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <!-- 3 -->
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" clearable placeholder="请选择部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <!-- 4 -->
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>
      <!-- 5 -->
      <el-form-item>
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
        <el-button size="mini" @click="$emit('cancel',false)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple, addDepartment, getDetails, editDepartment } from '@/api/department'
export default {
  name: 'DialogForm',
  props: {
    parentId: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 自定校验 重复部门编码
    const checkCode = (rules, value, callback) => {
      // 取出每一项的code 组成一个新数组
      let codeList = this.originList.map(item => item.code)
      // 如果是编辑 需要排除当前编辑项 取其他项的code
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(`编码${value}已经存在`)) : callback()
    }

    // 自定义校验部门名称
    const checkName = (rules, value, callback) => {
      // 找到当前父级id对应的子级pid 取出name 组成一个数组
      let nameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      console.log(nameList)
      // 编辑 需要排除当前编辑的一项的名字
      if (this.isEdit) {
        // 找到当前编辑项
        const nowItem = this.originList.find(item => item.id === this.parentId)
        const pid = nowItem.pid
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(`部门名称${value}已存在`)) : callback()
    }
    return {
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门负责人
        introduce: '' // 部门介绍
      },
      deptRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' }
        ]
      },
      employees: []
    }
  },
  // 会有卡顿 还是首选 v-if
  // watch: {
  //   // 监听父级id的变化 重新调用获取部门详情的函数
  //   parentId() {
  //     this.getDetails()
  //   }
  // },
  created() {
    // 获取简单负责人列表
    this.getEmployeeSimple()
    // 获取部门详情
    // 因为created只会执行一次 数据回填会有问题
    // 所以当点击关闭弹框按钮时,就销毁组件 点开的时候就会重新渲染组件 从而重新执行created
    this.getDetails()
  },
  methods: {
    // 获取部门详情
    async getDetails() {
      // 当处于编辑状态时,调用接口获取部门详情
      if (this.isEdit) {
        const res = await getDetails(this.parentId)
        // console.log(res)
        this.deptForm = res.data
      }
    },

    // 添加子部门
    onSubmit() {
      // 整体表单校验
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 校验通过
        if (this.isEdit) {
        // 编辑
          const res = await editDepartment(this.deptForm)
          // console.log(res)
          this.$emit('close')
          this.$message.success(res.message)
        } else {
        // 添加
          const params = { ...this.deptForm, pid: this.parentId }
          // console.log(params)
          // 调用api
          const res = await addDepartment(params)
          // console.log(res)
          // 成功关闭弹框 提示 更新树形结构
          // 清空表单内容
          // this.$nextTick(() => {
          //   this.$refs.form.resetFields()
          // })
          this.$emit('close')
          this.$message.success(res.message)
        }
      })
    },

    // 获取负责人列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res.data
    }
  }
}
</script>
<style scoped lang="scss">
.el-select {
  width: 100%;
}
.el-form {
  padding:0 60px 0 30px
}
</style>
